'use client';

/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import {
  Input,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Tooltip,
} from '@chakra-ui/react';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import Button, { ButtonSize, ButtonVariant } from '@/components/button/Button';
import SwitchButton from '@/components/button/SwitchButton';
import { AvatarMaskShape } from '@/components/image/Avatar';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Logo from '@/components/image/Logo';
import Link from '@/components/link/Link';
import EditPersonaModal from '@/components/modal/EditPersonaModal';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import InfoPill from '@/components/pill/InfoPill';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import TitleText from '@/components/title/TitleText';
import { toast } from '@/components/toast/Toast';
import TrashPersonaToast from '@/components/toast/TrashPersonaToast';
import {
  CreateIcon,
  HeartIcon,
  HeartOutlineIcon,
  MoreVerticalIcon,
  MusicIcon,
  PauseIcon,
  PlayIcon,
  TrashIcon,
  UserAddIcon,
  UserAddedIcon,
} from '@/icons';
import { ContextType } from '@/logging/contextTypes';
import logWebUserEvent, {
  createTransactionLogger,
} from '@/logging/logWebUserEvent';
import { Clip } from '@/state/clipStore';
import { Persona } from '@/state/personaStore';
import { FeatureKey, PlanFeature } from '@/state/sessionStore';
import {
  FALLBACK_IMAGE_URL,
  LARGE_IMAGE,
  MENUS_Z_INDEX,
  SMALL_IMAGE,
} from '@/utils/constants';
import { sharePersona } from '@/utils/download';
import { isFeatureEnabledForPlan } from '@/utils/session';
import { colorVar } from '@/utils/utils';

const PersonaHeader = observer(
  ({ persona: initialPersona, clips }: { persona: any; clips: Clip[] }) => {
    const {
      playbar,
      session,
      persona: personaStore,
      genForm,
      queue: queueStore,
      clips: clipStore,
      createV2,
      menus,
    } = useStores();
    const [localPersona, setLocalPersona] = useState(initialPersona);
    const [showTrashTooltip, setShowTrashTooltip] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [isFollowing, setIsFollowing] = useState(localPersona.is_following);
    const [followLoading, setFollowLoading] = useState(false);
    const [chatInput, setChatInput] = useState('');
    const [isCreateLoading, setIsCreateLoading] = useState(false);

    const router = useRouter();

    const handleImageClick = () => {
      if (localPersona?.is_owned) {
        setIsEditModalOpen(true);
      }
    };

    const handleTrashPersona = async () => {
      setLocalPersona((prev: Persona) => ({ ...prev, is_trashed: true }));

      try {
        const result = await personaStore.trashPersona(localPersona.id);
        if (result) {
          runInAction(() => {
            personaStore.updatePersona(localPersona.id, {
              ...localPersona,
              is_trashed: true,
            });
          });

          toast({
            duration: 4000,
            isClosable: true,
            position: 'bottom',
            render: ({ onClose }) => (
              <TrashPersonaToast
                persona={localPersona}
                undoTrash={() => undoTrashPersona(localPersona.id, onClose)}
              />
            ),
          });
          logWebUserEvent({
            actionName: 'TrashPersonaClicked',
            context: {
              personaId: localPersona?.id,
            },
          });
        } else {
          setLocalPersona((prev: Persona) => ({ ...prev, is_trashed: false }));
        }
      } catch (error) {
        console.error('Error trashing persona:', error);
        setLocalPersona((prev: Persona) => ({ ...prev, is_trashed: false }));
      }
    };

    const undoTrashPersona = async (personaId: string, onClose: () => void) => {
      try {
        const result = await personaStore.trashPersona(personaId, true);
        if (result) {
          setLocalPersona((prev: Persona) => ({ ...prev, is_trashed: false }));
          runInAction(() => {
            personaStore.updatePersona(personaId, {
              ...localPersona,
              is_trashed: false,
            });
          });

          onClose();
          toast({
            duration: 2000,
            isClosable: true,
            position: 'bottom',
            render: () => (
              <div className='flex items-center justify-between rounded-md bg-dumbo-900 p-3 font-sans text-dumbo-50'>
                <p>
                  <b>{localPersona.name}</b> restored to library
                </p>
              </div>
            ),
          });
        }
      } catch (error) {
        console.error('Error undoing trash persona:', error);
      }
    };

    const handlePersonaUpdate = (updatedPersona: Persona) => {
      setLocalPersona(updatedPersona);
      runInAction(() => {
        personaStore.updatePersona(updatedPersona.id, updatedPersona);
      });
      logWebUserEvent({
        actionName: 'UpdatePersonaClicked',
        context: {
          personaId: localPersona?.id,
        },
      });
    };

    const handleMoreActionsChange = (key: string) => {
      if (key === 'trash') {
        handleTrashPersona();
      } else if (key === 'restore') {
        undoTrashPersona(localPersona.id, () => {});
        logWebUserEvent({
          actionName: 'UndoTrashPersonaClicked',
          context: {
            personaId: localPersona?.id,
          },
        });
      } else if (key === 'edit') {
        setIsEditModalOpen(true);
        logWebUserEvent({
          actionName: 'EditPersonaClicked',
          context: {
            personaId: localPersona?.id,
          },
        });
      }
    };

    const handleTogglePublic = async () => {
      const newPublicState = !localPersona.is_public;
      setLocalPersona((prev: any) => ({ ...prev, is_public: newPublicState }));

      try {
        const result = await personaStore.setPersonaVisibility(
          localPersona.id,
          newPublicState
        );
        toast({
          title: `Persona is now ${newPublicState ? 'public' : 'private'}.`,
          duration: 2000,
          isClosable: true,
        });
        if (!result) {
          throw new Error('Failed to update persona visibility');
        }
      } catch (error) {
        setLocalPersona((prev: any) => ({
          ...prev,
          is_public: !newPublicState,
        }));
        toast({
          title: 'Error',
          description: 'Failed to update persona visibility. Please try again.',
          status: 'error',
          duration: 3000,
          isClosable: true,
        });
      }
      logWebUserEvent({
        actionName: 'TogglePersonaPublicClicked',
        context: {
          personaId: localPersona?.id,
          publicState: newPublicState ? 'on' : 'off',
        },
      });
    };

    const handleCreateSong = () => {
      genForm.setPersona(initialPersona.id);
      genForm.setPersonaClipId(initialPersona?.clip?.id);

      createV2.resetPlaylistConditioning();
      createV2.resetPainting();

      genForm.setTask('artist_consistency');
      genForm.setStyle(initialPersona?.clip.metadata?.tags || '');
      genForm.setNegativeTags(
        initialPersona?.clip.metadata?.negative_tags || ''
      );
      if (initialPersona?.clip.metadata?.negative_tags !== '') {
        genForm.setEnableExcludeStyle(true);
      }
      createV2.setActivePersona(initialPersona);

      logWebUserEvent({
        actionName: 'CreateSongFromPersonaButtonClicked',
        context: {
          personaId: initialPersona?.id,
        },
      });

      const clipId = initialPersona?.clip?.id;
      if (clipId) {
        router.push('/create?use_persona=' + clipId);
      } else {
        router.push('/create');
      }
    };

    const handleToggleLove = async () => {
      try {
        const result = await personaStore.toggleLovePersona(localPersona.id);
        if (result) {
          setLocalPersona((prev: Persona) => ({
            ...prev,
            is_loved: result.loved,
            upvote_count: result.upvote_count,
          }));
          logWebUserEvent({
            actionName: 'TogglePersonaLoveClicked',
            context: {
              personaId: localPersona?.id,
              personaLovedState: result.loved ? 'on' : 'off',
            },
          });
        }
      } catch (error) {
        console.error('Error toggling persona love:', error);
        toast({
          title: 'Error',
          description:
            'Failed to update persona love status. Please try again.',
          status: 'error',
          duration: 3000,
          isClosable: true,
        });
      }
    };

    const handleToggleFollow = async () => {
      setFollowLoading(true);
      try {
        await personaStore.toggleFollowPersona(localPersona?.id, isFollowing);
        setIsFollowing(!isFollowing);
      } catch (error) {
        toast({
          title: 'Error',
          description: 'Failed to update follow status. Please try again.',
          status: 'error',
          duration: 3000,
          isClosable: true,
        });
      } finally {
        setFollowLoading(false);
      }
    };

    const handleSunoPersonaCreate = async () => {
      setIsCreateLoading(true);

      genForm.setStyle(initialPersona?.clip?.metadata?.tags || '');
      genForm.setPersona(localPersona.id);
      genForm.setPersonaClipId(localPersona?.clip?.id);
      createV2.resetPlaylistConditioning();
      createV2.resetPainting();
      genForm.setTask('artist_consistency');
      genForm.setLyricsModel('lorenzo-v1');
      genForm.setLyricsPrompt(chatInput);
      genForm.setIsLoading(true);

      try {
        await genForm.generateLyrics(chatInput);

        if (!genForm.lyrics) {
          throw new Error('No lyrics generated');
        }

        const transactionLogger = createTransactionLogger();
        await clipStore.runStream({ transactionLogger, session });

        genForm.setIsLoading(false);

        const clipId = initialPersona?.clip?.id;
        if (clipId) {
          router.push('/create?use_persona=' + clipId);
        } else {
          router.push('/create');
        }
      } catch (e) {
        genForm.setIsLoading(false);
        setIsCreateLoading(false);
        toast({
          title: 'Error',
          description: 'An error occurred while generating the song.',
          status: 'error',
          duration: 5000,
          isClosable: true,
        });
        return;
      }
    };

    if (
      session.flags?.['suno-persona-proto'] &&
      initialPersona.is_suno_persona
    ) {
      return (
        <div className='relative w-full' style={{ height: '420px' }}>
          {/* Background with Linear Gradient */}
          <div
            className='absolute inset-0 h-full w-full'
            style={{
              background:
                'linear-gradient(to right, #D160D2 0%, #0e8774 1080%)',
            }}
          />

          {/* Gradient Overlay */}
          <div className='absolute inset-0 bg-linear-to-t from-background-primary via-background-primary/40 to-transparent' />

          {/* Content Container */}
          <div className='relative z-10 h-full'>
            {/* Concentric Persona Shapes */}
            <div className='absolute top-0 left-[25%] h-full w-full overflow-hidden'>
              <div
                className='absolute inset-0 scale-80 transform animate-persona-ripple-1 bg-white/9 backdrop-blur-sm'
                style={AvatarMaskShape.Persona}
              />
              <div
                className='absolute inset-0 scale-90 transform animate-persona-ripple-2 bg-white/10 backdrop-blur-sm'
                style={AvatarMaskShape.Persona}
              />
              <div
                className='absolute inset-0 scale-90 transform animate-persona-ripple-3 bg-white/4 backdrop-blur-sm'
                style={AvatarMaskShape.Persona}
              />
            </div>

            {/* Chat Section */}
            <div className='absolute top-0 left-0 flex animate-pop-in items-center gap-4 p-6'>
              {/* Profile Image */}
              <div className='relative h-40 w-40'>
                <div
                  className='absolute inset-0'
                  style={AvatarMaskShape.Persona}
                >
                  <ImageWithFallback
                    imageSize={LARGE_IMAGE}
                    className='h-full w-full object-cover'
                    src={
                      initialPersona.image_s3_id ||
                      initialPersona.clip?.image_url ||
                      FALLBACK_IMAGE_URL
                    }
                    alt={`Persona image for ${initialPersona.name}`}
                  />
                </div>
                <div
                  className='absolute right-2 -bottom-1 flex h-12 w-12 items-center justify-center'
                  style={{
                    background:
                      'radial-gradient(circle at center, rgba(255,107,44,0.3) 0%, rgba(255,107,44,0) 70%)',
                  }}
                >
                  <div className='relative flex h-10 w-10 items-center justify-center overflow-hidden rounded-full'>
                    <ImageWithFallback
                      src={FALLBACK_IMAGE_URL}
                      alt='Background'
                      className='absolute inset-0 h-full w-full object-cover'
                    />
                    <Logo className='relative z-10 h-6 w-6' />
                  </div>
                </div>
              </div>

              {/* Chat Content */}
              <div className='flex flex-col gap-2'>
                <div className='rounded-[32px] rounded-tl-[2px] bg-[rgba(255,255,255,0.1)] px-5 py-3 backdrop-blur-sm'>
                  <p className='overflow-hidden text-lg whitespace-nowrap text-white'>
                    I can motivate you through any challenge! What task are you
                    dreading, champ?
                  </p>
                </div>
                <div className='flex items-center gap-2'>
                  <Input
                    placeholder="I don't want to fold my laundry"
                    className='w-[200px] rounded-[32px] bg-[rgba(255,255,255,0.1)] px-5 py-3 text-lg text-white backdrop-blur-sm'
                    value={chatInput}
                    onChange={(e) => setChatInput(e.target.value)}
                    _placeholder={{ color: 'rgba(255,255,255,0.5)' }}
                    border='1px solid rgba(255,255,255,0.3)'
                    _focus={{
                      boxShadow: 'none',
                      border: '1px solid rgba(255,255,255,0.3)',
                    }}
                    bg='rgba(255,255,255,0.1)'
                    _hover={{ bg: 'rgba(255,255,255,0.1)' }}
                    borderRadius='32px'
                  />
                  <Button
                    variant={ButtonVariant.Primary}
                    onClick={handleSunoPersonaCreate}
                    disabled={!chatInput.trim() || isCreateLoading}
                    className='rounded-full'
                    icon={
                      isCreateLoading ? (
                        <SpinnerSVG className='mx-1 fill-current' />
                      ) : undefined
                    }
                  >
                    {isCreateLoading ? '' : 'Create'}
                  </Button>
                </div>
              </div>
            </div>

            {/* Main Content Area */}
            <div className='absolute right-0 bottom-0 left-0 px-8 pb-6'>
              <div className='flex items-end gap-12'>
                {/* Middle Content */}
                <div className='grow pb-2'>
                  <div className='flex flex-col gap-5'>
                    {/* Title and Description */}
                    <div className='text-left'>
                      <h1 className='mb-2 font-serif text-6xl font-light text-white'>
                        {initialPersona.name}
                      </h1>
                      <p className='max-w-2xl text-sm text-[#B4B4B4]'>
                        {initialPersona.description}
                      </p>
                    </div>
                    <div className='flex items-center gap-6'>
                      {/* Action Buttons */}
                      <div className='flex gap-2'>
                        <Tooltip
                          color={'white'}
                          background={colorVar('background/primary')}
                          label={
                            !isFeatureEnabledForPlan(
                              session,
                              PlanFeature.Persona
                            )
                              ? 'Subscribe to create a song with Personas'
                              : !localPersona.is_public &&
                                  !localPersona.is_owned
                                ? 'You cannot create a song with a non-public Persona.'
                                : 'Create a song with this Persona'
                          }
                        >
                          <Button
                            size={ButtonSize.Large}
                            onClick={() => {
                              if (
                                !isFeatureEnabledForPlan(
                                  session,
                                  PlanFeature.Persona
                                )
                              ) {
                                menus.setCurrentUpsellFeature(
                                  FeatureKey.PERSONAS
                                );
                                menus.openModal(ModalTypes.UPSELL_MODAL);
                              } else if (
                                localPersona.is_public ||
                                localPersona.is_owned
                              ) {
                                handleCreateSong();
                              }
                            }}
                            disabled={
                              !isFeatureEnabledForPlan(
                                session,
                                PlanFeature.Persona
                              )
                            }
                            variant={ButtonVariant.Primary}
                            icon={
                              <CreateIcon className='h-5 w-5 fill-current' />
                            }
                          >
                            <span className='block sm:hidden'>Create</span>
                            <span className='hidden whitespace-nowrap sm:block'>
                              Use Persona
                            </span>
                          </Button>
                        </Tooltip>
                        {session.flags?.['personas-follow'] &&
                          !localPersona.is_owned &&
                          !localPersona.is_trashed &&
                          isFeatureEnabledForPlan(
                            session,
                            PlanFeature.Persona
                          ) && (
                            <Tooltip
                              color={'white'}
                              background={colorVar('background/primary')}
                              label={
                                isFollowing
                                  ? 'Unfollow this Persona'
                                  : 'Follow this Persona'
                              }
                            >
                              <Button
                                size={ButtonSize.Large}
                                icon={
                                  followLoading ? (
                                    <SpinnerSVG />
                                  ) : isFollowing ? (
                                    <UserAddedIcon className='h-4 w-4' />
                                  ) : (
                                    <UserAddIcon className='h-4 w-4' />
                                  )
                                }
                                variant={
                                  isFollowing
                                    ? ButtonVariant.Primary
                                    : ButtonVariant.Secondary
                                }
                                onClick={handleToggleFollow}
                                disabled={followLoading}
                              />
                            </Tooltip>
                          )}
                        <div className='relative'>
                          <Tooltip
                            color={'white'}
                            background={colorVar('background/primary')}
                            label={
                              localPersona.is_loved
                                ? 'Remove this Persona from favorites'
                                : 'Favorite this Persona'
                            }
                          >
                            <Button
                              size={ButtonSize.Large}
                              onClick={handleToggleLove}
                              variant={ButtonVariant.Secondary}
                              active={localPersona.is_loved}
                              icon={
                                localPersona.is_loved
                                  ? HeartIcon
                                  : HeartOutlineIcon
                              }
                            />
                          </Tooltip>
                        </div>
                        {clips.length > 0 && (
                          <Tooltip
                            color={'white'}
                            background={colorVar('background/primary')}
                            label="Play this Persona's songs"
                          >
                            <Button
                              size={ButtonSize.Large}
                              variant={ButtonVariant.Primary}
                              icon={
                                queueStore.contextType ===
                                  ContextType.Persona &&
                                queueStore.contextId === localPersona.id &&
                                playbar.isPlaying
                                  ? PauseIcon
                                  : PlayIcon
                              }
                              onClick={() => {
                                if ((clips || []).length > 0) {
                                  if (
                                    queueStore.contextType ===
                                      ContextType.Persona &&
                                    queueStore.contextId === localPersona.id
                                  ) {
                                    playbar.togglePlay();
                                    return;
                                  }
                                  queueStore.setPlayContext({
                                    contextType: ContextType.Persona,
                                    contextId: localPersona.id,
                                    clips,
                                    currentIndex: 0,
                                  });
                                  playbar.playClip(clips[0]);
                                }
                                logWebUserEvent({
                                  actionName: 'PersonaPlayButtonClicked',
                                  context: {
                                    personaId: localPersona?.id,
                                  },
                                });
                              }}
                            />
                          </Tooltip>
                        )}
                      </div>

                      {/* Divider */}
                      <div className='h-6 w-px bg-white/20' />

                      {/* Stats */}
                      <div className='flex items-center gap-6'>
                        <div className='flex gap-2'>
                          <InfoPill
                            text={
                              clips.length === 1
                                ? '1 SONG'
                                : `${clips.length} SONGS`
                            }
                            icon={
                              <MusicIcon className='h-3 w-3 fill-primary' />
                            }
                            tooltip={
                              localPersona?.is_owned
                                ? 'Showing only public songs and the root song from which you created the Persona'
                                : undefined
                            }
                          />
                          <InfoPill
                            text={`${localPersona.upvote_count || 0} ${(localPersona.upvote_count || 0) === 1 ? 'LOVE' : 'LOVES'}`}
                            icon={
                              <HeartIcon className='h-3 w-3 fill-primary' />
                            }
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          {localPersona.is_suno_persona && localPersona.is_owned && (
            <EditPersonaModal
              isOpen={isEditModalOpen}
              onClose={() => setIsEditModalOpen(false)}
              persona={localPersona}
              onUpdate={handlePersonaUpdate}
            />
          )}
        </div>
      );
    }

    return (
      <div className='z-20 flex flex-col items-start gap-8 px-4 pt-16 pb-8 lg:flex-row lg:p-8'>
        <div className='flex w-full grow flex-col gap-8 lg:flex-row'>
          <div
            className={`relative h-56 w-56 ${localPersona?.is_owned ? 'cursor-pointer' : ''} mx-0`}
            onClick={handleImageClick}
          >
            <div className='relative h-56 w-56'>
              <div
                className='absolute top-1/2 left-1/2 h-[95%] w-[95%] -translate-x-1/2 -translate-y-1/2 transform overflow-hidden'
                style={AvatarMaskShape.Persona}
              >
                <ImageWithFallback
                  imageSize={LARGE_IMAGE}
                  className='h-full w-full object-cover'
                  src={
                    localPersona.image_s3_id ||
                    localPersona.clip?.image_url ||
                    FALLBACK_IMAGE_URL
                  }
                  alt={`Persona image for ${localPersona.name}`}
                />
              </div>
            </div>
          </div>
          <div className='flex w-full grow flex-col pt-2'>
            <div className='flex h-full flex-col justify-between lg:flex-row'>
              <div className='flex grow flex-col justify-between'>
                <div className='flex w-full items-center justify-between'>
                  <div className='flex items-center'>
                    <TitleText text={localPersona.name} />
                    {localPersona.is_trashed && (
                      <div
                        className='ml-2 rounded-full bg-accent-pink p-1.5'
                        onMouseEnter={() => setShowTrashTooltip(true)}
                        onMouseLeave={() => setShowTrashTooltip(false)}
                      >
                        <TrashIcon className='h-3 w-3 fill-white' />
                        {showTrashTooltip && (
                          <div className='absolute z-10 mt-2 w-40 rounded bg-accent-pink p-2 font-sans text-sm text-primary shadow-md'>
                            This persona has been moved to the trash.
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                  <div className='mt-2 flex items-center xl:mt-0'>
                    {localPersona.is_owned && (
                      <SwitchButton
                        buttonText='Public'
                        onChange={handleTogglePublic}
                        checked={localPersona.is_public}
                      />
                    )}
                  </div>
                </div>
                <div className='my-0 flex items-center font-sans text-sm text-foreground-primary'>
                  <div className='mr-2'>By</div>
                  <ImageWithFallback
                    className='mr-2 h-6 w-6 rounded-full'
                    src={localPersona.user_image_url || null}
                    imageSize={SMALL_IMAGE}
                    alt='User avatar'
                  />
                  <div className='hover:underline'>
                    <Link href={`/@${localPersona.user_handle}`}>
                      {localPersona.user_display_name ||
                        localPersona.user_handle}
                    </Link>
                  </div>
                </div>
                <div className='py-4 font-sans text-sm text-foreground-primary'>
                  {localPersona.description}
                </div>
                <div className='flex flex-row items-center gap-2'>
                  <InfoPill
                    text={
                      clips.length === 1 ? '1 SONG' : `${clips.length} SONGS`
                    }
                    icon={<MusicIcon className='h-3 w-3 fill-primary' />}
                    tooltip={
                      localPersona?.is_owned
                        ? 'Showing only public songs and the root song from which you created the Persona'
                        : undefined
                    }
                  />
                  <InfoPill
                    text={`${localPersona.upvote_count || 0} ${(localPersona.upvote_count || 0) === 1 ? 'LOVE' : 'LOVES'}`}
                    icon={<HeartIcon className='h-3 w-3 fill-primary' />}
                  />
                </div>
                <div className='mt-4 flex flex-col items-start justify-between xl:flex-row xl:items-center'>
                  <div className='mb-2 flex items-center gap-2 xl:mb-0'>
                    <Tooltip
                      color={'white'}
                      background={colorVar('background/primary')}
                      label={
                        !isFeatureEnabledForPlan(session, PlanFeature.Persona)
                          ? 'Subscribe to create a song with Personas'
                          : !localPersona.is_public && !localPersona.is_owned
                            ? 'You cannot create a song with a non-public Persona.'
                            : 'Create a song with this Persona'
                      }
                    >
                      <Button
                        size={ButtonSize.Large}
                        onClick={() => {
                          if (
                            !isFeatureEnabledForPlan(
                              session,
                              PlanFeature.Persona
                            )
                          ) {
                            menus.setCurrentUpsellFeature(FeatureKey.PERSONAS);
                            menus.openModal(ModalTypes.UPSELL_MODAL);
                          } else if (
                            localPersona.is_public ||
                            localPersona.is_owned
                          ) {
                            handleCreateSong();
                          }
                        }}
                        disabled={
                          !isFeatureEnabledForPlan(session, PlanFeature.Persona)
                        }
                        variant={ButtonVariant.Primary}
                        icon={CreateIcon}
                      >
                        <span className='block sm:hidden'>Create</span>
                        <span className='hidden whitespace-nowrap sm:block'>
                          Create with Persona
                        </span>
                      </Button>
                    </Tooltip>
                    {session.flags?.['personas-follow'] &&
                      !localPersona.is_owned &&
                      !localPersona.is_trashed &&
                      isFeatureEnabledForPlan(session, PlanFeature.Persona) && (
                        <Tooltip
                          color={'white'}
                          background={colorVar('background/primary')}
                          label={
                            isFollowing
                              ? 'Unfollow this Persona'
                              : 'Follow this Persona'
                          }
                        >
                          <Button
                            size={ButtonSize.Large}
                            icon={
                              followLoading ? (
                                <SpinnerSVG />
                              ) : isFollowing ? (
                                <UserAddedIcon className='h-4 w-4' />
                              ) : (
                                <UserAddIcon className='h-4 w-4' />
                              )
                            }
                            variant={
                              isFollowing
                                ? ButtonVariant.Primary
                                : ButtonVariant.Secondary
                            }
                            onClick={handleToggleFollow}
                            disabled={followLoading}
                          />
                        </Tooltip>
                      )}
                    <div className='relative'>
                      <Tooltip
                        color={'white'}
                        background={colorVar('background/primary')}
                        label={
                          localPersona.is_loved
                            ? 'Remove this Persona from favorites'
                            : 'Favorite this Persona'
                        }
                      >
                        <Button
                          size={ButtonSize.Large}
                          onClick={handleToggleLove}
                          variant={ButtonVariant.Secondary}
                          active={localPersona.is_loved}
                          icon={
                            localPersona.is_loved ? HeartIcon : HeartOutlineIcon
                          }
                        />
                      </Tooltip>
                    </div>

                    {clips.length > 0 && (
                      <Tooltip
                        color={'white'}
                        background={colorVar('background/primary')}
                        label="Play this Persona's songs"
                      >
                        <Button
                          size={ButtonSize.Large}
                          variant={ButtonVariant.Primary}
                          icon={
                            queueStore.contextType === ContextType.Persona &&
                            queueStore.contextId === localPersona.id &&
                            playbar.isPlaying
                              ? PauseIcon
                              : PlayIcon
                          }
                          onClick={() => {
                            if ((clips || []).length > 0) {
                              if (
                                queueStore.contextType ===
                                  ContextType.Persona &&
                                queueStore.contextId === localPersona.id
                              ) {
                                playbar.togglePlay();
                                return;
                              }
                              queueStore.setPlayContext({
                                contextType: ContextType.Persona,
                                contextId: localPersona.id,
                                clips,
                                currentIndex: 0,
                              });
                              playbar.playClip(clips[0]);
                            }
                            logWebUserEvent({
                              actionName: 'PersonaPlayButtonClicked',
                              context: {
                                personaId: localPersona?.id,
                              },
                            });
                          }}
                        />
                      </Tooltip>
                    )}
                    <div className='relative'>
                      <Menu>
                        <MenuButton
                          as={Button}
                          variant={ButtonVariant.Primary}
                          size={ButtonSize.Large}
                          aria-label='More options'
                          className='pr-2 pl-4'
                          icon={MoreVerticalIcon}
                        />
                        <MenuList zIndex={MENUS_Z_INDEX} sx={{ bg: '#252020' }}>
                          <MenuItem
                            bg={'transparent'}
                            fontFamily={'Neue Montreal'}
                            _hover={{
                              background: 'rgba(255, 255, 255, 0.1)',
                            }}
                            onClick={() => {
                              setIsEditModalOpen(true);
                              logWebUserEvent({
                                actionName: 'EditPersonaClicked',
                                context: {
                                  personaId: localPersona?.id,
                                },
                              });
                            }}
                          >
                            Edit
                          </MenuItem>
                          <MenuItem
                            bg={'transparent'}
                            fontFamily={'Neue Montreal'}
                            _hover={{
                              background: 'rgba(255, 255, 255, 0.1)',
                            }}
                            onClick={() => {
                              sharePersona({
                                id: localPersona.id,
                                name: localPersona.name,
                              });
                            }}
                          >
                            Share
                          </MenuItem>
                          {localPersona.is_trashed ? (
                            <MenuItem
                              bg={'transparent'}
                              fontFamily={'Neue Montreal'}
                              _hover={{
                                background: 'rgba(255, 255, 255, 0.1)',
                              }}
                              onClick={() => handleMoreActionsChange('restore')}
                            >
                              Restore to Library
                            </MenuItem>
                          ) : (
                            <MenuItem
                              bg={'transparent'}
                              fontFamily={'Neue Montreal'}
                              _hover={{
                                background: 'rgba(255, 255, 255, 0.1)',
                              }}
                              onClick={() => handleMoreActionsChange('trash')}
                            >
                              Move to Trash
                            </MenuItem>
                          )}
                        </MenuList>
                      </Menu>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <EditPersonaModal
          isOpen={isEditModalOpen}
          onClose={() => setIsEditModalOpen(false)}
          persona={localPersona}
          onUpdate={handlePersonaUpdate}
        />
      </div>
    );
  }
);

export default PersonaHeader;
